#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
完整系统演示脚本
展示模式记忆与马尔可夫链结合以及多算法融合功能
"""

import os
import sys
import time
import random
import pandas as pd
import numpy as np

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 导入需要的模块
from lottery_predictor_app import LotteryPredictorApp
from algorithms.prediction_fusion import PredictionFusion
from algorithms.markov_chain_model import PLWMarkovChainModel

# 创建一个简化版本的预测器类
class SimplePredictor:
    def __init__(self):
        self.base_dir = os.path.dirname(os.path.abspath(__file__))
        
    def execute_single_algorithm(self, method, lottery_type, num_predictions):
        app = LotteryPredictorApp.__new__(LotteryPredictorApp)
        app.base_dir = self.base_dir
        
        # 初始化必要的属性
        app.algorithm_priorities = {
            "lstm_crf": 1,
            "enhanced_lstm": 2,
            "gradient_boost": 3,
            "memory_network": 4,
            "weighted_expert": 5,
            "markov_chain": 6
        }
        
        if method == "lstm_crf":
            return app.get_lstm_crf_predictions(lottery_type, num_predictions)
        elif method == "memory_network":
            return app.get_memory_network_predictions(lottery_type, num_predictions)
        elif method == "markov_chain":
            return app.get_markov_chain_predictions(lottery_type, num_predictions)
        elif method == "memory_markov_combined":
            return app.get_memory_markov_combined_predictions(lottery_type, num_predictions)
        elif method == "gradient_boost":
            return app.get_gradient_boost_predictions(lottery_type, num_predictions)
        elif method == "weighted_expert":
            return app.get_weighted_expert_predictions(lottery_type, num_predictions)
        else:
            raise ValueError(f"不支持的算法方法: {method}")
    
    def get_lstm_crf_predictions(self, lottery_type, num_predictions):
        app = LotteryPredictorApp.__new__(LotteryPredictorApp)
        app.base_dir = self.base_dir
        return app.get_lstm_crf_predictions(lottery_type, num_predictions)
        
    def get_memory_network_predictions(self, lottery_type, num_predictions):
        app = LotteryPredictorApp.__new__(LotteryPredictorApp)
        app.base_dir = self.base_dir
        return app.get_memory_network_predictions(lottery_type, num_predictions)
        
    def get_markov_chain_predictions(self, lottery_type, num_predictions):
        app = LotteryPredictorApp.__new__(LotteryPredictorApp)
        app.base_dir = self.base_dir
        return app.get_markov_chain_predictions(lottery_type, num_predictions)
        
    def get_memory_markov_combined_predictions(self, lottery_type, num_predictions):
        app = LotteryPredictorApp.__new__(LotteryPredictorApp)
        app.base_dir = self.base_dir
        return app.get_memory_markov_combined_predictions(lottery_type, num_predictions)

def demo_complete_system():
    """演示完整系统功能"""
    print("🎯 彩票预测系统完整功能演示")
    print("=" * 60)
    
    # 创建预测器实例
    predictor = SimplePredictor()
    
    # 测试排列5预测
    lottery_type = "plw"
    num_predictions = 3
    
    print(f"📋 测试彩票类型: 排列5 (plw)")
    print(f" 生成预测数量: {num_predictions}")
    print()
    
    # 1. 测试独立算法
    print(" 1. 独立算法预测")
    print("-" * 30)
    
    # 模式记忆网络模式
    print("   模式记忆 网络模式:")
    try:
        memory_preds = predictor.get_memory_network_predictions(lottery_type, num_predictions)
        for i, pred in enumerate(memory_preds):
            print(f"    预测 {i+1}: {pred['red']}")
    except Exception as e:
        print(f"    ❌ 执行失败: {e}")
    
    # 马尔可夫链模型
    print("  🔗 马尔可夫链 模型:")
    try:
        markov_preds = predictor.get_markov_chain_predictions(lottery_type, num_predictions)
        for i, pred in enumerate(markov_preds):
            print(f"    预测 {i+1}: {pred['red']}")
    except Exception as e:
        print(f"    ❌ 执行失败: {e}")
    
    print()
    
    # 2. 测试模式记忆与马尔可夫链结合
    print("🤝 2. 模式记忆与马尔可夫链结合预测")
    print("-" * 30)
    
    try:
        combined_preds = predictor.get_memory_markov_combined_predictions(lottery_type, num_predictions)
        for i, pred in enumerate(combined_preds):
            print(f"    预测 {i+1}: {pred['red']} (置信度: {pred.get('confidence', 0.5):.3f})")
    except Exception as e:
        print(f"    ❌ 执行失败: {e}")
    
    print()
    
    # 3. 测试多算法融合
    print("⚖️ 3. 多算法预测结果融合")
    print("-" * 30)
    
    # 收集所有算法的预测结果
    all_predictions = {}
    
    # 获取各算法预测结果
    algorithms = ["memory_network", "markov_chain"]
    algorithm_names = {
        "memory_network": "模式记忆 网络模式", 
        "markov_chain": "马尔可夫链 模型"
    }
    
    for algo in algorithms:
        try:
            preds = predictor.execute_single_algorithm(algo, lottery_type, num_predictions)
            all_predictions[algo] = preds
            print(f"  ✅ {algorithm_names[algo]} 预测完成")
        except Exception as e:
            print(f"  ❌ {algorithm_names[algo]} 预测失败: {e}")
    
    # 使用融合机制
    if all_predictions:
        fusion = PredictionFusion()
        
        # 重新组织数据格式
        fusion_input = {}
        for algo, preds in all_predictions.items():
            fusion_input[algo] = preds[:num_predictions]  # 确保数量一致
        
        # 加权平均融合
        print("  🔗 基于优先级的加权平均融合:")
        try:
            fused_results = fusion.weighted_average_fusion(fusion_input)
            for i, result in enumerate(fused_results):
                print(f"    融合预测 {i+1}: {result['red']} (置信度: {result['confidence']:.3f})")
                print(f"      权重: {result['algorithm_weights']}")
        except Exception as e:
            print(f"    ❌ 融合失败: {e}")
        
        # 置信度加权融合
        print("  ⚖️ 基于置信度的加权融合:")
        try:
            confidence_fused_results = fusion.confidence_weighted_fusion(fusion_input)
            for i, result in enumerate(confidence_fused_results):
                print(f"    置信度融合 {i+1}: {result['red']} (置信度: {result['confidence']:.3f})")
                print(f"      权重: {result['algorithm_weights']}")
        except Exception as e:
            print(f"    ❌ 置信度融合失败: {e}")
    
    print()
    print("🎉 演示完成!")
    print()
    print("📝 系统特性总结:")
    print("  ✅ 6种独立预测算法")
    print("  ✅ 模式记忆与马尔可夫链智能结合")
    print("  ✅ 基于优先级的加权平均融合")
    print("  ✅ 基于置信度的动态权重融合")
    print("  ✅ 完整的多算法对比预测系统")

if __name__ == "__main__":
    demo_complete_system()